package com.qu.waibao.account;

import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MainActivity;
import com.qu.waibao.R;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.XiuAuthenticActivity;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class BindPhoneActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.tv_code)
    TextView tv_code;
    @BindView(R.id.tv_car)
    TextView tv_car;
    @BindView(R.id.tv_shop)
    TextView tv_shop;
    @BindView(R.id.tv_xiu)
    TextView tv_xiu;
    private String role = "";
    private String thirdlogintype = "";
    private String smscode = "";
    private CountDownTimerUtil countDownTimerUtil;

    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            thirdlogintype = bundle.getString("thirdlogintype","");
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_bind_phone;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        countDownTimerUtil = new CountDownTimerUtil(60000,1000);
        tv_title.setText("绑定手机号");
        iv_publish.setVisibility(View.GONE);
        tv_sure.setVisibility(View.VISIBLE);
        tv_sure.setText("取消");
        ll_back.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        super.initData();
    }
    @OnClick({R.id.tv_code,R.id.tv_sure,R.id.tv_car,R.id.tv_shop,R.id.tv_xiu,R.id.tv_login})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_code:
                String phone = et_phone.getText().toString();
                if(TextUtils.isEmpty(phone)){
                    ToastUtil.show(this,"请输入手机号");
                    return;
                }else if(phone.length() != 11){
                    ToastUtil.show(this,"输入手机号格式有误");
                    return;
                }
                getCode(phone);
                break;
            case R.id.tv_sure:
                finish();
                break;
            case R.id.tv_car:
                role = "1";
                tv_car.setSelected(true);
                tv_shop.setSelected(false);
                tv_xiu.setSelected(false);
                break;
            case R.id.tv_shop:
                role = "3";
                tv_car.setSelected(false);
                tv_shop.setSelected(true);
                tv_xiu.setSelected(false);
                break;
            case R.id.tv_xiu:
                role = "2";
                tv_car.setSelected(false);
                tv_shop.setSelected(false);
                tv_xiu.setSelected(true);
                break;
            case R.id.tv_login:
                String phones = et_phone.getText().toString();
                String code = et_code.getText().toString();
                if(TextUtils.isEmpty(phones)){
                    ToastUtil.show(this,"请输入手机号");
                    return;
                }else if(phones.length() != 11){
                    ToastUtil.show(this,"输入手机号格式有误");
                    return;
                }else if(TextUtils.isEmpty(code)){
                    ToastUtil.show(this,"请输入验证码");
                    return;
                }else if(!code.equals(smscode)){
                    ToastUtil.show(this,"输入验证码有误");
                    return;
                }else if(TextUtils.isEmpty(role)){
                    ToastUtil.show(this,"请选择注册用户");
                    return;
                }
                login(phones);
                break;
        }
    }

    public class CountDownTimerUtil extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountDownTimerUtil(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv_code.setText(millisUntilFinished/1000+"s");
        }

        @Override
        public void onFinish() {
            tv_code.setEnabled(true);
            tv_code.setText("重新发送");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(countDownTimerUtil != null){
            countDownTimerUtil.cancel();
            countDownTimerUtil = null;
        }
    }

    public void getCode(String phone){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.get_code);
        map.put("phone",phone);
        if(thirdlogintype.equals("1")){
            map.put("type","4");
        }else {
            map.put("type","5");
        }
        NetManager.getInstance().request(this, map, true,
                new XnetCallBack() {
                    @Override
                    public void onSuccess(String result, String msg) {
                        countDownTimerUtil.start();
                        tv_code.setEnabled(false);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            smscode = jsonObject.optString("smscode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
    }

    public void login(String phone){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.phone_bind_set);
        map.put("userid", AppConfig.getString("userid"));
        map.put("phone",phone);
        map.put("thirdlogintype",thirdlogintype);
        map.put("role",role);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int role = jsonObject.optInt("role");
                    String state = jsonObject.optString("state_check");
                    String userid = jsonObject.optString("userid");
                    AppConfig.saveInt("card",role);
                    AppConfig.saveString("state_check",state);
                    AppConfig.saveString("userid",userid);
                    initChat(userid,jsonObject.optString("pwd"),role);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 阿里百川的聊天
     */
    private void initChat(String userid, String pwd, final int role) {
        YWIMKit mIMKit = YWAPI.getIMKitInstance(userid, AppConfig.APP_KEY);
        IYWLoginService loginService = mIMKit.getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userid,pwd);
        loginService.login(loginParam, new IWxCallback() {
            @Override
            public void onSuccess(Object... arg0) {
                ToastUtil.show(BindPhoneActivity.this,"绑定手机号成功");
                if(role == 1){
                    startActivity(new Intent(BindPhoneActivity.this,MainActivity.class));
                }else if(role == 2){
                    startActivity(new Intent(BindPhoneActivity.this,XiuAuthonticActivity.class));
                }else if(role == 3){
                    startActivity(new Intent(BindPhoneActivity.this,ShopAuthonticActivity.class));
                }
                finish();
            }
            @Override
            public void onProgress(int arg0) {}
            @Override
            public void onError(int errCode, String description) {
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
                Log.e("TAG","description----"+description+"errCode-----"+errCode);
            }
        });
    }
}
